﻿using System;
using System.Drawing;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace RGB.SharePoint.Util.SPExtendedImageField
{

	/// <summary>
	/// Holds width and height of a picture
	/// </summary>
	public struct Dimension
	{

		public int Width { get; set; }
		public int Height { get; set; }
	}

	/// <summary>
	/// Resize the picture dimensions
	/// </summary>
	public static class Resizer
	{
		public static Dimension GetMiniature(int width, int height)
		{
			Dimension dimensions = new Dimension();
			// Initialize the value of the dimension
			dimensions.Width = width;
			dimensions.Height = height;

			// Get the ratio between the height and the width
			float ratio = (float)dimensions.Height / dimensions.Width;

			// Resiez the dimension
			if (dimensions.Height > 200 || dimensions.Width > 200)
			{
				if (dimensions.Height > dimensions.Width)
				{
					dimensions.Height = 200;
					dimensions.Width = (int)(200 / ratio);
				}
				else
				{
					dimensions.Width = 200;
					dimensions.Height = (int)(200 * ratio);
				}
			}
			return dimensions;
		}
	}

	/// <summary>
	/// ChoosePicture.aspx code behind
	/// </summary>
	public class ChoosePicture : LayoutsPageBase
	{
		// Upload control
		protected FileUpload uploader;

		/// <summary>
		/// Click on the cancel button
		/// </summary>
		protected void btnCancel_Click(object sender, EventArgs e)
		{
			// Close the page
			Page.Response.Write(@"<script language='javascript'>window.close();</script>");
		}

		/// <summary>
		/// Click on the upload button
		/// </summary>
		protected void btnUpload_Click(object sender, EventArgs e)
		{

			// If no file has been selected, leave the function
			if (uploader.FileBytes.Length == 0 || string.IsNullOrEmpty(uploader.FileName))
				return;

			// Granting privileges
			SPSecurity.RunWithElevatedPrivileges(delegate
													 {

														 Guid guid = Guid.NewGuid();

														 // Picture Library
														 SPPictureLibrary list;

														 try
														 {
															 // Retrieve a reference to the picture library
															 list = (SPPictureLibrary)Site.RootWeb.Lists["Image Picker Picture List"];
														 }
														 catch
														 {
															 // If the library "Image Picker Picture Library" doesn't exists, create the list
															 Guid listGuid = Site.RootWeb.Lists.Add("Image Picker Picture List", SPUtility.GetLocalizedString("$Resources:ListDescription", "SPExtendedImageField", SPContext.Current.Web.Language), SPListTemplateType.PictureLibrary);

															 list = (SPPictureLibrary)Site.RootWeb.Lists[listGuid];
															 list.OnQuickLaunch = false;
															 list.Update();

														 }

														 // Add the picture in the library
														 SPFile it = list.RootFolder.Files.Add(guid + uploader.FileName.Substring(uploader.FileName.LastIndexOf('.')), uploader.FileBytes, true);
														 // Update the item
														 it.Update();

														 // Create the Bitmap from the uploaded picture
														 Bitmap image = new Bitmap(uploader.FileContent);

														 // Get the dimension of the miniature
														 Dimension dimensions = Resizer.GetMiniature(image.Width, image.Height);

														 // Changing the picture of the parent page
														 Page.Response.Write(@"<script language='javascript'>
																				opener.document.getElementById('" + Page.Request.QueryString["GUID"] + @"').src = '" + list.ParentWeb.Site.Url + "/" + it.Url + @"';
																				opener.document.getElementById('" + Page.Request.QueryString["GUID"] + @"').style.visibility = 'visible';
																				opener.document.getElementById('" + Page.Request.QueryString["GUID"] + @"').style.width = '" + dimensions.Width + @"px';
																				opener.document.getElementById('" + Page.Request.QueryString["GUID"] + @"').style.height = '" + dimensions.Height + @"px';
																				opener.document.getElementById('" + Page.Request.QueryString["path"] + "').value = '" + list.ParentWeb.Site.Url + "/" + it.Url + @"'
																				window.close();
																			  </script>");
													 });
		}
	}
}
